package com.spzx.product.controller;

import com.alibaba.excel.EasyExcel;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.product.domain.Category;
import com.spzx.product.domain.vo.CategoryExcelVo;
import com.spzx.product.listener.ExcelCategoryListener;
import com.spzx.product.service.CategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Tag(name = "商品分类接口管理")
@RestController
@RequestMapping("/productUnit")
public class CategoryController extends BaseController {

    @Autowired
    private CategoryService categoryService;

    @Operation(summary = "")
    @GetMapping("/list/{id}")
    public AjaxResult list(@PathVariable Long id){
        List<Category> list = categoryService.listTree(id);
        return success(list);
    }
    //导出
    @PostMapping("/export")
    public void export(HttpServletResponse response){
        categoryService.export(response);
    }

    //导入
    //使用MultipartFile获取上传文件
    @PostMapping("/import")
    public AjaxResult importData(MultipartFile file){//参数文件file编写规则:要和name值一致
        try{
            categoryService.importData(file);
            return AjaxResult.success("导入成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.success("导入失败");
    }

    //带监听器读写法
    public void importData1(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream())
                    .head(CategoryExcelVo.class)
                    .sheet()
                    .registerReadListener(new ExcelCategoryListener(categoryService))
                    .doRead();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
